// 供应商货品
// 作者：洪刚

const express = require("express");
const db = require("../model/db");
const router = express.Router();

// 添加供应商货品
router.post("/add", async (req, res) => {
    if (!req.query.supplierId) {
        req.query.supplierId = {}
    }
    const data = await db.Suppliergoods.create(req.body);
    res.send(true)
})

// 得到所有货品
router.get("/all", async (req, res) => {
    let page = parseInt(req.query.page);
    let limit = parseInt(req.query.limit);
    if (!page) {
        page = 1;
    }
    if (!limit) {
        limit = 10;
    }
    let connection = {};  //条件对象
    if (req.query.key) {
        const exp = new RegExp(req.query.key, "i")//不区分大小写，模糊查询正则表达式
        connection = {
            $or: [
                { nickname: { $regex: exp } },   //货品名字
                { category: { $regex: exp } }, //类别
                { material: { $regex: exp } }, //材质类别
            ]
        }
    }
    const data = await db.Suppliergoods.find(connection).skip((page - 1) * limit).limit(limit);
    const count = await db.Suppliergoods.countDocuments(connection);
    res.send({
        code: 0,
        msg: "",
        count,
        data
    });
})

// 查看单个货品
router.get("/:id", async (req, res) => {
    const data = await db.Suppliergoods.findById(req.params.id);
    const count = await db.Suppliergoods.countDocuments(data);
    res.send({
        code: 0,
        msg: "",
        count: count,
        data: data
    })
})

// 修改货品
router.put("/:id", async (req, res) => {
   await db.Suppliergoods.updateOne(
        {_id: req.params.id},req.body)
    res.send(true)
})

//删除货品
router.delete("/:id", async (req, res) => {
    await db.Suppliergoods.deleteOne({
        _id: req.params.id
    })
    res.send(true);
})

module.exports = router;